import { getReportData } from '@/api/report/overview'
import { parseTime, toFixed, isNumber } from '@/utils'
import { DATE_TYPE, INDICATORS } from './constant'
const dateFmt = '{y}-{m}-{d}'
const prefixUrl = process.env.VUE_APP_SUPERSET_SERVER
const indicatorOrder = INDICATORS.reduce((obj, item, index) => {
  obj[item] = index
  return obj
}, {})
export default {
  methods: {
    getParameter (params = {}) {
      const query = {}
      for (const key in params) {
        let val = params[key]
        if (key === 'time_range') {
          const timeRange = this.getFinalDateRange(params)
          val = `${timeRange[0] + 'T00:00:00'} : ${timeRange[1] + 'T23:59:59'}`
        } else if (Array.isArray(val)) {
          val = val.join(',')
        }
        val !== '' && (query[key] = val)
      }
      return query
    },
    getChartData (params = {}) {
      return getReportData(this.getParameter(params))
    },
    // 获取页面url
    getIframeSrc (params = {}) {
      const query = this.getParameter(params)
      return `${prefixUrl}api/v1/data_report/chart/iframe?${Object.keys(query).map(key => (key + '=' + query[key])).join('&')}`
    },
    // 获取实际传入后端的时间
    getFinalDateRange (params, num) {
      const { time_range, time_grain_sqla } = params
      const timeRange = Array.isArray(time_range) ? time_range : [time_range, time_range]
      let d1 = new Date(timeRange[0])
      let d2 = new Date(timeRange[1])
      let d3 = null
      let d4 = null
      switch (time_grain_sqla) {
        case DATE_TYPE.DAY: // 天
          if (num) {
            const day1 = d1.getDate()
            const day2 = d2.getDate()
            d3 = parseTime(new Date(d1).setDate(day1 - num), dateFmt)
            d4 = parseTime(new Date(d2).setDate(day2 - num), dateFmt)
          }
          break
        case DATE_TYPE.WEEK: // 周
          const w1 = d1.getDay()
          const w2 = d2.getDay()
          w1 !== 1 && (d1 = new Date(d1.setDate(d1.getDate() - (w1 === 0 ? 7 : w1) + 1)))
          w2 !== 0 && (d2 = new Date(d2.setDate(d2.getDate() + 7 - w2)))
          if (num) {
            const day1 = d1.getDate()
            const day2 = d2.getDate()
            d3 = parseTime(new Date(d1).setDate(day1 - num * 7), dateFmt)
            d4 = parseTime(new Date(d2).setDate(day2 - num * 7), dateFmt)
          }
          break
        case DATE_TYPE.MONTH: // 月
          d1 = new Date(d1.setDate(1))
          d2 = new Date(d2.setDate(new Date(d2.getFullYear(), d2.getMonth() + 1, 0).getDate()))
          if (num) {
            const m1 = d1.getMonth()
            const m2 = d2.getMonth()
            d3 = parseTime(new Date(d1).setMonth(m1 - num), dateFmt)
            d4 = parseTime(new Date(d2).setMonth(m2 - num), dateFmt)
          }
          break
      }

      return [parseTime(d1, dateFmt), parseTime(d2, dateFmt), d3, d4]
    },
    // 获取环比周期
    getLastPeriod (params) {
      const { time_range, time_grain_sqla } = params
      const d1 = new Date(time_range[0])
      const d2 = new Date(time_range[1])
      switch (time_grain_sqla) {
        case DATE_TYPE.DAY: // 天
          const dayDiff = (d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24 + 1
          d1.setDate(d1.getDate() - dayDiff)
          d2.setDate(d2.getDate() - dayDiff)
          break
        case DATE_TYPE.WEEK: // 周
          {
            const w1 = d1.getDay()
            const w2 = d2.getDay()
            w1 !== 1 && d1.setDate(d1.getDate() - (w1 === 0 ? 7 : w1) + 1)
            w2 !== 0 && d2.setDate(d2.getDate() + 7 - w2)
            const dayDiff = (d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24 + 1
            d1.setDate(d1.getDate() - dayDiff)
            d2.setDate(d2.getDate() - dayDiff)
          }
          break
        case DATE_TYPE.MONTH: // 月
          const monthDiff = (d2.getFullYear() - d1.getFullYear()) * 12 + d2.getMonth() - d1.getMonth() + 1
          d1.setDate(1)
          d2.setDate(1)
          d1.setMonth(d1.getMonth() - monthDiff)
          d2.setMonth(d2.getMonth() - monthDiff)
          // 设置为月的最后一天
          d2.setDate(new Date(d2.getFullYear(), d2.getMonth() + 1, 0).getDate())
          break
      }
      return [parseTime(d1, dateFmt), parseTime(d2, dateFmt)]
    },
    // 格式化表格日期
    fmtTableDate (date, type) {
      const d = new Date(date)
      let dateStr = parseTime(d, dateFmt)
      switch (type) {
        case DATE_TYPE.HOUR: // 小时
          // 需要减去8小时
          dateStr = parseTime(d.getTime() - 8 * 60 * 60 * 1000, dateFmt + ' {h}:{i}')
          break
        case DATE_TYPE.DAY: // 天
          dateStr += `（${'日一二三四五六'.charAt(d.getDay())}）`
          break
        case DATE_TYPE.WEEK: // 周
          dateStr += '（周）'
          break
        case DATE_TYPE.MONTH: // 月
          dateStr = dateStr.slice(0, 7) + '（月）'
          break
      }
      return dateStr
    },
    // 对指标进行排序
    indicatorSort (list, key = 'name') {
      return list.sort((a, b) => indicatorOrder[a[key]] - indicatorOrder[b[key]])
    },
    // 根据名称来格式化数字
    formatNumber (val, name) {
      return toFixed(val * this.getMultiNum(name), this.getDecimalNum(name))
    },
    // 根据中文名称获取保留小数点位数
    getDecimalNum (name) {
      let num = 0
      if (name.includes('率') || ['交易总额', '交易客单价', '交易笔单价'].includes(name)) {
        num = 2
      }
      return num
    },
    // 根据中文名称获取放大倍数
    getMultiNum (name) {
      return name.includes('率') ? 100 : 1
    },
    isNumber (val) {
      return isNumber(val)
    }
  },
  computed: {
    indicatorList () {
      return this.indicatorOpts.reduce((arr, item) => {
        Array.isArray(item.children) && arr.push(...item.children)
        return arr
      }, [])
    },
    indicatorMap () {
      return this.indicatorList.reduce((obj, item) => {
        obj[item.label] = item.value
        return obj
      }, {})
    }
  }
}
